package org.example.stockservice.service;

import lombok.RequiredArgsConstructor;
import org.example.stockservice.dao.StockEntity;
import org.example.stockservice.dao.StockRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StockService {
    @Autowired
    private StockRepository repository;

    @Transactional(rollbackFor = Exception.class)
    public void deduct(String commodityCode, int count){
        StockEntity stock = repository.findByCommodityCode(commodityCode)
                .orElseThrow(() -> new RuntimeException("商品不存在"));
        if (stock.getCount() < count){
            throw new RuntimeException("库存不足");
        }
        stock.setCount(stock.getCount() - count);
        repository.save(stock);
    }
}